package com.lj.common.utils.ip;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lj.common.config.LjConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取地址类
 *
 * @author 小李飞刀
 */
@Slf4j
public class AddressUtil {

    /**
     * P地址查询
     */
    public static final String IP_URL = "https://whois.pconline.com.cn/ipJson.jsp";

    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip) {
        // 内网不查询
        if (IpUtil.internalIp(ip)) {
            return "内网IP";
        }
        if (LjConfig.isAddressEnabled()) {
            try {
                String rspStr = HttpUtil.get(IP_URL + "?ip=124.93.57.10" + "&json=true", CharsetUtil.CHARSET_GBK);
                if (CharSequenceUtil.isEmpty(rspStr)) {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSONObject.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            } catch (Exception e) {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }

    public static void main(String[] args) {

        String rspStr = HttpUtil.get(IP_URL + "?ip=124.93.57.10" + "&json=true", CharsetUtil.CHARSET_GBK);
        System.out.println(rspStr);
    }
}